import GoogleMapReact from 'google-map-react';
import * as React from 'react';
import styles from './index.module.scss';
import {logger} from 'ice';
import {Form, Input, Loading, Message} from '@alifd/next';
import MapDataConfirmModel from './MapDataConfirmModel';

let markers = [];
const sleep = () => {
  return new Promise(resolve => setTimeout(() => {
    resolve()
  }, 500))
}
const Map = () => {
  const [mapData, setMapData] = React.useState({
    center: {
      lat: 22.7743005,
      lng: 107.3273202,
    },
    zoom: 9,
  });

  const [loadingConfig, setLoadingConfig] = React.useState({
    visible: false,
    tip: '',
  });

  const [items, setItems] = React.useState([])

  const done = () => {
    setUx();
  };

  const reducer = (_state, action) => {
    switch (action?.type) {
      case 'confirm':
        return <MapDataConfirmModel done={done} items={action.items}/>;
      default:
        return <></>;
    }
  };

  const [$ux, setUx] = React.useReducer(reducer, <></>);

  const setInput = (items) => {
    const type = 'confirm';
    setUx({type, items});
  };

  const {location, map} = mapData;
  const serviceRef = React.useRef({});

  const onApiLoaded = (map) => {
    serviceRef.current.placeService = new google.maps.places.PlacesService(map);
    serviceRef.current.geocoderService = new google.maps.Geocoder(map);
    ;
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (geo) => {
          const {coords: {latitude: lat, longitude: lng}} = geo;
          setMapData({...mapData, map, location: {lat, lng}});
        },
        (...error) => {
          setMapData({...mapData, map});
        },
      );
    } else {
      setMapData({...mapData, map});
    }
  };

  const onSearch = async (form, error) => {
    if (error) return;
    const {keyword} = form;
    const keywords = keyword.split(';').filter(x => x).map(x => x.trim());
    const {placeService, geocoderService} = serviceRef.current;

    setLoadingConfig({
      visible: true,
      tip: '查询中',
    });


    const queryRlts = []
    try {
      for (let i = 0; i < keywords.length; i++) {
        const query = keywords[i]

        const title = `${i + 1}/${keywords.length}:${query}`
        setLoadingConfig({
          visible: true,
          tip: `${title}...`,
        });
        const datas = (await new Promise((resolve) => {
          const params = {
            query,
            fields: ['html_attributions'],
            // region:null,
            // sensor:true,
            bounds:new google.maps.LatLngBounds()
          };
          const searchRlts = [];
          placeService.textSearch(params, (rlt, status, pagination) => {
            if (status === 'OK') {
              logger.debug('rlt',rlt)
              searchRlts.push(rlt);
              if (pagination.hasNextPage) {
                pagination.nextPage();
              } else {
                resolve(searchRlts);
              }
            } else {
              resolve(searchRlts);
            }
          });
        })).flat(2);
        for (let j = 0; j < datas.length; j++) {

          setLoadingConfig({
            visible: true,
            tip: `${title} 获取详情 ${j}/${datas.length}`,
          });


          const searchData = datas[j]
          const {
            types,
            name,
            formatted_address,
            place_id: placeId,
            geometry: {location}
          } = searchData;

          const lat = location.lat();
          const lng = location.lng();
          const data = {name, types, formatted_address, location: [lat, lng]};
          const detail = await new Promise((resolve) => {
            placeService.getDetails({
              placeId,
              fields: ['name', 'rating', 'website', 'formatted_phone_number', 'geometry','reviews','type'],
            }, (detail, status) => {
              if (status === 'OK') {
                logger.debug('detail',detail)
                const {formatted_phone_number, website} = detail;
                resolve({...data, website, formatted_phone_number});
              } else {
                logger.error('detail fail',status,detail)
                resolve(data);
              }
            });
          });
          await sleep()
          queryRlts.push(detail);
        }
      }

    } finally {
      setLoadingConfig({
        ...loadingConfig,
        visible: false,
      });
    }


    if (queryRlts.length === 0) {
      Message.error('未能找到相应数据');
    } else {
      setItems(queryRlts)
      setInput(queryRlts);
    }
  };

  React.useEffect(() => {
    if (map) {
      const bounds = new google.maps.LatLngBounds();
      for (const marker of markers) {
        marker.setMap(null)
      }
      markers = []
      for (const item of items) {
        const {location: [lat, lng]} = item
        logger.debug('items', item)
        const marker = new google.maps.Marker({
          position: {
            lat, lng
          },
          map,
          title: "Hello World!",
        });
        markers.push(marker)
        bounds.extend(marker.getPosition())
      }
      if (markers.length !== 0) {

        map.fitBounds(bounds);
      }
    }

  }, [items, map]);

  const onMapClick = ({lat, lng}) => {
    setMapData({...mapData, location: {lat, lng}});
  };

  return (
    <Loading {...loadingConfig} size={'large'}>
      {$ux}
      <div className={styles.container}>
        <div className={styles.map_wrapper}>
          <GoogleMapReact
            bootstrapURLKeys={{
              key: 'AIzaSyAqbeDZZT675DRqRT3dfJp-w6hEBeNxDEA',
              libraries: ['places'],
            }}
            yesIWantToUseGoogleMapApiInternals
            defaultCenter={mapData.center}
            defaultZoom={mapData.zoom}
            onClick={onMapClick}
            onGoogleApiLoaded={({map, maps}) => onApiLoaded(map, maps)}
          />
        </div>
        <div className={styles.panel}>
          <Form>
            <Form.Item required requiredMessage={'请输入关键词'}>
              <Input.TextArea
                name="keyword"
                placeholder={'请输入关键词 多个以分好分开'}
                style={{width: '95%'}}
                autoHeight={{minRows: 15}}
                // defaultValue={'Electronics manufacturer'}
              />
            </Form.Item>
            <Form.Item>
              <Form.Submit validate onClick={onSearch} type={'primary'}
                           style={{width: '50%'}}>查询</Form.Submit>
            </Form.Item>
          </Form>

        </div>
      </div>
    </Loading>
  );
};

export default Map;
